#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-

import time
import zipfile
import shutil
import json
import os
import sys
import re
from Script import *
from Common import *

import sys
path = sys.path.append("..")


class exportNodesFile(object):

    def __init__(self, outputpath, *zipfilepath):
        self.outputpath = outputpath
        self.zipfilepath = zipfilepath

    # 解压zip
    # @zip包路径
    # @解压输出路径
    # @资源文件命名
    def unZip(self):

        zipLength = len(self.zipfilepath)
        print("共有" + str(zipLength) + "个压缩包")
        for zippath in self.zipfilepath:
            # print(zippath)
            if(os.path.exists(zippath)):
                pass
            else:
                print("其中" + zippath + " 路径不存在....无法生成贴纸,程序退出")
                exit(0)

        # 解压路径都存在，开始解压
        print("——————————开始解压————————————")
        for zippath in self.zipfilepath:
            zipfiles = zipfile.ZipFile(zippath, "r")
            zipfiles.extractall(self.outputpath)
            zipfiles.close()

    # 解析Json
    # # @json文件路径
    def loadjson(self, jsonPath, fileName, outPath,productName):
        # print(jsonPath)
        if(os.path.exists(jsonPath)):
            # 根据json文件的路径截取该文件所在目录、json文件全称
            # json父级别文件路径
            parentPath = splitStringByIndex(
                jsonPath, splitString(jsonPath, "/"), 0)
            # json文件名称
            jsonName = splitStringByIndex(splitString(jsonPath, "/"), ".", 0)

            global jsonContent, scriptNameList

            print("——————————开始解析json文件——————————")
            jsonContent, scriptNameList = analysisJson(jsonPath, fileName)
            print("——————————完成json文件的解析——————————")
            if os.path.exists(parentPath):
                self.__copyCommonRescource(parentPath, fileName)
                self.__createPassthrongh(outPath)
                content = self.__getCommonScriptContent(parentPath, fileName)
                content, paramContent, selfFunctionContent = self.__getZipScriptContent(parentPath, fileName, scriptNameList, content, "")
                self._writeLuaFile(paramContent, content, fileName)
                self._removeLuaFile(productName)

        else:
            print(jsonPath + " 路径下的该文件不存在")
    def _removeLuaFile(self, productName):
        if os.path.exists(currentpath+"/Product/"+productName+"/"+productName+"/script"):
            pass
        else:         
            os.makedirs(currentpath+"/Product/"+productName+"/"+productName) 
        copyDir(currentpath +"/Sticker/Sticker/",currentpath+"/Product/"+productName+"/"+productName+"/script")
        

        
    def _writeLuaFile(self, paramContent, content, fileName):
        f = open(currentpath+"/Sticker/Sticker/"+str(fileName)+".lua", "w+")
        f.write(content)
        f.close()
        if os.path.exists(currentpath+"/Sticker/Sticker/"+"TS.lua"):
            os.remove(currentpath+"/Sticker/Sticker/"+"TS.lua")
    # @私有
    # #拆分变量内容得到应该替换为self.param的变量

    def _splitParamContent(self, param):

        pos1 = param.find("=")
        pos2 = param.find(",")
        if pos1 != -1:
            return str(param[:pos1])

    # @私有
    # #填充lua文件
    # 生成Script类型的内容
    def __getZipScriptContent(self, parentPath, fileName, scriptNameList, content, paramContent):
        selfFunctionContent = []
        if scriptNameList:
            for index, value in enumerate(scriptNameList):
                content, paramContent, selfFunctionContent = analysisScript(parentPath+value+"/index.lua", fileName, content)
                copyDir(parentPath+value+"/img", currentpath +
                        "/Sticker/Sticker/"+str(fileName)+"/img/")
        return content, paramContent, selfFunctionContent

    # @私有
    # #填充lua文件

    def __getCommonScriptContent(self, parentPath, jsonName):

        commonLuaFilePath = os.getcwd()+"/NodeFile/Common.lua"

        commonFile = open(commonLuaFilePath, "r+")
        content = commonFile.read()

        pos = content.find("jsonContent")
        if pos != -1:
            length = len("jsonContent")
            content = replaceStr(pos, content, length, jsonContent)

        pos = content.find("CommonNode")
        res = jsonName
        while pos != -1:

            length = len("CommonNode")

            content = replaceStr(pos, content, length, res)
            pos = pos+1
            pos = content.find("CommonNode", pos)

        commonFile.close()

        if (os.path.exists(os.getcwd()+"/Package/Kuru_warp/kuru_wrap.lua")):
            shutil.copy(os.getcwd()+"/Package/Kuru_warp/kuru_wrap.lua",
                        parentPath + "/" + str(jsonName) + "/")
        return content

    # @私有
    # #填充lua文件
    def __createPassthrongh(self, outPath):
        passthroughpath = outPath+"/passthrough.frag"
        print("这是"+outPath)
        if (os.path.exists(passthroughpath)):
            return
        else:
            fo = open(passthroughpath, "w")
            contents = [
                "void mainImage( out vec4 fragColor, in vec2 fragCoord )",
                "{",
                "vec2 uv = fragCoord.xy / iResolution.xy;",
                "fragColor = texture(iChannel0, uv);",
                "}"
            ]

            for line in contents:
                fo.write(line + "\n")
            fo.close()

    # @私有
    # #在json文件同级目录生成同名包，并将资源导入
    def __copyCommonRescource(self, parentPath, jsonName):

        nodeFile = parentPath + "/" + str(jsonName)
        os.mkdir(nodeFile)
        desfolder = nodeFile + "/img/"
        copySpecialFile(parentPath, desfolder, ".png")

        desfolder = nodeFile + "/filter/"
        copySpecialFile(parentPath, desfolder, ".dat")

    def copyLuaFile(self, sourcefolder, createFileName):
        desfolder = createFileName
        copySpecialFile(sourcefolder, desfolder, ".lua")

    # 复制lua模块路径
    def copyModle(self, modlePath, luaName):
        copyModles(modlePath, luaName)

    # 复制资源
    # @资源路径
    def copyRescource(self, sourcefolder, createFileName):
         # 复制指定类型的文件到某路径下
        desfolder = createFileName + "/img/"
        copySpecialFile(sourcefolder, desfolder, ".png")

        desfolder = createFileName + "/filter/"
        copySpecialFile(sourcefolder, desfolder, ".dat")
        print("copyRescource"+os.getcwd())
